package cn.xkai.exercise.a;

/**
 * @description: 买卖股票的最佳时机 II
 * 自己的思路：双指针套路，当自己前面的数比自己大时说明需要卖出，并且当前值作为新的买入点，卖出时计算卖出点-买入点的数据并累加起来
 * 借鉴的思路：贪心算法
 * 心得：随着index的增长减少了循环次数（以一次完整下跌到一次完整上涨的过程作为一次循环）
 * @author: kaixiang
 * @date: 2022-06-30
 **/
public class Solution23 {
    public int maxProfit(int[] prices) {
        if (prices.length == 1) {
            return 0;
        }
        int left = 0, right = 1, profit = 0;
        while (right < prices.length) {
            if (prices[right - 1] >= prices[right]) {
                if (left < right - 1) {
                    profit += prices[right - 1] - prices[left];
                }
                left = right;
            }
            if (right == prices.length - 1) {
                profit += prices[right] - prices[left];
            }
            right++;
        }
        return profit;
    }

    public int maxProfixRefer(int[] prices) {
        if (prices == null || prices.length < 2)
            return 0;
        int total = 0, index = 0, length = prices.length;
        while (index < length) {
            //如果股票下跌就一直找，直到找到股票开始上涨为止
            while (index < length - 1 && prices[index] >= prices[index + 1])
                index++;
            //股票上涨开始的值，也就是这段时间上涨的最小值
            int min = prices[index];
            //一直找到股票上涨的最大值为止
            while (index < length - 1 && prices[index] <= prices[index + 1])
                index++;
            //计算这段上涨时间的差值，然后累加
            total += prices[index++] - min;
        }
        return total;
    }

    public static void main(String[] args) {
        int[] prices = {7, 1, 5, 3, 6, 4};
        Solution23 solution23 = new Solution23();
        System.out.println(solution23.maxProfit(prices));
    }
}
